
/**
 * 等比图放大使用
 * @param{Element}  。enlarge1
 * @returns 等比显示图
 */

class Enlarge{
    constructor(el){
        this.el=document.querySelector(el)
        this.imgObj=this.el.querySelector('.img')
        this.maskObj=this.el.querySelector('.mask')
        this.enlargeObj=this.el.querySelector('.enlarge')
        this.init()
    }
    init(){
        this.overOut()
        this.enlargeSetWH()
        this.maskMove()
    }
    maskMove(){
        this.imgObj.onmousemove=(evt)=>{
            let e=evt || window.event
            let left=e.pageX-this.imgObj.offsetLeft-this.maskObj.offsetWidth/2
            let top =e.pageY-this.imgObj.offsetTop -this.maskObj.offsetHeight/2

            if(left<0) left=0
            if(top<0) top=0
            let maxLeft=this.el.clientWitdh -this.maskObj.offsetWidth
            let maxTop =this.el.clientHeight-this.maskObj.offsetHeight
            if(left>maxLeft) left=maxLeft
            if(top>maxTop) left=maxTop
            this.maskObj.style.left=left+'px'
            this.maskObj.style.top=top+'px'

            this.enlargesetBg(left,top)
        }
    }
    enlargesetBg(left,top){
        let enlargeBgsize=(this.getStyle(this.enlargeObj,'background-size')).split(' ')
        let enlargeBgW=parseInt(enlargeBgsize[0])
        let enlargeBgH=parseInt(enlargeBgsize[1])

        let imgW=parseInt(this.getStyle(this.imgObj,'width'))
        let imgH=parseInt(this.getStyle(this.imgObj,'height'))

        let x=left*(enlargeBgW/imgW)
        let y=top *(enlargeBgH/imgH)
        this.enlargeObj.style.backgroundPosition=`-${x}px -${y}px`
    }
    getStyle(tagObj,cssAttr){
        return window.getComputedStyle ? window.getComputedStyle(tagObj)[cssAttr] : tagObj.currentStyle[cssAttr]
    }
    enlargeSetWH(){
        let maskW=parseInt(this.getStyle(this.maskObj,'width'))
        let maskH=parseInt(this.getStyle(this.maskObj,'height'))
 
        let enlargeBgsize=(this.getStyle(this.enlargeObj,'background-size')).split(' ')
        let enlargeBgW=parseInt(enlargeBgsize[0])
        let enlargeBgH=parseInt(enlargeBgsize[1])

        let imgW=parseInt(this.getStyle(this.imgObj,'width'))
        let imgH=parseInt(this.getStyle(this.imgObj,'height'))

        let w=maskW*(enlargeBgW/imgW)
        let h=maskH*(enlargeBgH/imgH)
        this.enlargeObj.style.width=w+'px'
        this.enlargeObj.style.height=h+'px'
    }
    overOut(){
        this.imgObj.onmouseover = () => this.maskObj.style.display = this.enlargeObj.style.display = 'block'
        this.imgObj.onmouseout  = () => this.maskObj.style.display = this.enlargeObj.style.display = ''
    }
}

export default Enlarge;